<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width = device-width, initial-scale = 1.0, minimum-scale = 1.0, maximum-scale = 1.0, user-scalable = no"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta name="renderer" content="webkit">
<meta name="msapplication-tap-highlight" content="no" /><!-- winphone 点击无高光 -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<title>哈哈哈</title>
</head>
<body>
<style>
html,body,p,h1,h2,h3,h4,h5,h6,form,input,textarea,select,button,fieldset,legend,img,ul,ol,li,dl,dt,dd,th,td,pre,blockquote{margin:0;padding:0}
img{max-width:100%;opacity:0;transition:opacity 2s}
.lazy{opacity:1;}
</style><div>却说姜维献计于马遵曰：“诸葛亮必伏兵于郡后，赚我兵出城，乘虚袭我。某愿请精兵三千，伏于要路。太守随后发兵出城，不可远去，止行三十里便回；但看火起为号，前后夹攻，可获大胜。如诸葛亮自来，必为某所擒矣。”遵用其计，付精兵与姜维去讫，然后自与梁虔引兵出城等候；</div>
<div style="color:#38f;">皮搋子490kb</div>
<img class="lazy" _src="https://wx2.sinaimg.cn/mw1024/9ed5c127gy1fqwrtg4a1ej20j61zjx6q.jpg" alt="">
<div>只留梁绪、尹赏守城。原来孔明果遣赵云引一军埋伏于山僻之中，只待天水人马离城，便乘虚袭之。当日细作回报赵云，说天水太守马遵，起兵出城，只留文官守城。赵云大喜，又令人报与张翼、高翔，教于要路截杀马遵。此二处兵亦是孔明预先埋伏。却说赵云引五千兵，径投天水郡城下，高叫曰：“吾乃常山赵子龙也！汝知中计，早献城池，免遭诛戮！<span style="color:#38f;">下方有图片734kb</span></div>
<img class="lazy" _src="https://wx1.sinaimg.cn/mw690/4711809egy1fqq0vm2oyuj20w03404qt.jpg" alt="">

<div>城上梁绪大笑曰：“汝中吾姜伯约之计，尚然不知耶？”云恰待攻城，忽然喊声大震，四面火光冲天。当先一员少年将军，挺枪跃马而言曰：“汝见天水姜伯约乎！”云挺枪直取姜维。战不数合，维精神倍长。云大惊，暗忖曰：“谁想此处有这般人物！”正战时，两路军夹攻来，乃是马遵、梁虔引军杀回。赵云首尾不能相顾，冲开条路，引败兵奔走，姜维赶来。亏得张翼、高翔两路军杀出，接应回去。 赵云归见孔明，说中了敌人之计。孔明惊问曰：“此是何人，识吾玄机？”有南安人告曰：“此人姓姜，名维，字伯约，天水冀人也；事母至孝，文武双全，智勇足备，真当世之英杰也。”赵云又夸奖姜维枪法，与他人大不同。<span style="color:#38f;">下方有图片</span></div>
<img class="lazy" _src="https://wx2.sinaimg.cn/mw690/9ed5c127gy1fqwrjgssgqj20j61ys4pc.jpg" alt="">

<div>孔明曰：“吾今欲取天水，不想有此人。”遂起大军前来。<span style="color:#38f;">下方有图片</span></div>
<img class="lazy" _src="https://wx1.sinaimg.cn/mw690/603327d9ly1fqrajj4nbpj20u03q37mc.jpg" alt="">
<div> 却说姜维回见马遵曰：“赵云败去，孔明必然自来。彼料我军必在城中。今可将本部军马，分为四枝：某引一军伏于城东，如彼兵到则截之。太守与梁虔、尹赏各引一军城外埋伏。梁绪率百姓在城上守御。”分拨已定。<span style="color:#38f;">下面这个是故意错误的图片</span></div>
<img class="lazy" _src="https://wx4.si11111111111111naimg.cn/mw690/b1b2087ely1fqr6rjn8b1j20hs0htdrf.jpg">
<div>  却说孔明因虑姜维，自为前部，望天水郡进发。<span style="color:#38f;">下方有图片</span></div>
<img class="lazy" _src="https://wx4.sinaimg.cn/mw690/b1b2087ely1fqr6rjn8b1j20hs0htdrf.jpg" style="height:30px;">
<div>将到城边，孔明传令曰：“凡攻城池，以初到之日，<span style="color:#38f;">下方有图片</span></div>
<img class="lazy" _src="https://wx2.sinaimg.cn/mw690/5e9fdd85gy1fqrgzgv47aj20yi1pcqv5.jpg">
<div>激励三军，鼓噪直上。若迟延日久，锐气尽隳，急难破矣。”于是大军径到城下。因见城上旗帜整齐，未敢轻攻。候至半夜，忽然四下火光冲天，喊声震地，正不知何处兵来。只见城上亦鼓噪呐喊相应，蜀兵乱窜。孔明急上马，有关兴；张苞二将保护，杀出重围。回头看时，正东上军马，一带火光，势若长蛇。孔明令关兴探视，回报曰：“此姜维兵也。”孔明叹曰：“兵不在多，在人之调遣耳。此人真将才也！”收兵归寨，思之良久，乃唤安定人问曰：“姜维之母，现在何处？”答曰：“维母今居冀县。”孔明唤魏延分付曰：“汝可引一军，虚张声势，诈取冀县。若姜维到，可放入城。”又问：“此地何处紧要？”安定人曰：“天水钱粮，皆在上圭阝；若打破上圭阝，则粮道自绝矣。”孔明大喜，教赵云引一军去攻上圭阝。孔明离城三十里下寨。早有人报入天水郡，说蜀兵分为三路：一军守此郡，一军取上圭阝，一军取冀城。姜维闻之，哀告马遵曰：“维母现在冀城，恐母有失。维乞一军往救此城，兼保老母。”马遵从之，遂令姜维引三千军去保冀城；梁虔引三千军去保上圭阝。</div>
<div>却说姜维引兵至冀城，前面一彪军摆开，为首蜀将，乃是魏延。二将交锋数合，延诈败奔走。<span style="color:#38f;">下方有图片</span></div>
<img class="lazy" _src="https://wx1.sinaimg.cn/mw690/c5131475ly1fqvmcqy6ifj20c8328njm.jpg" >
<div id="fff"></div>
<div id="add" style="position:fixed;top:0px;right:0;background:#f00;color:#fff;">新增一个图片</div>
<div id="genxin" style="position:fixed;top:20px;right:0;background:#38f;color:#fff;">更新dom信息</div>
<div onclick="init()">init初始化</div>

<script>
	//todo list
	//重复区域用function封装
	//图片loading时候的状态,可以考虑直接在src里写上loading的gif
function lazyImg() {
    this.h = document.documentElement.clientHeight || document.body.clientHeight;
    this.lazyImg = document.getElementsByClassName('lazy')
    this.arrLazy = []
    this.tupian = ''
    this.forceAbort = false
    this.currentDomTuPian = null
    for (var i = 0; i < this.lazyImg.length; i++) {
        if (!this.lazyImg[i].isLoad) {
            this.arrLazy.push(this.lazyImg[i]);
        }
    }
    this.run = function () {
        var that = this
        if (that.currentDomTuPian && that.currentDomTuPian.getBoundingClientRect().top >= 0 && that.currentDomTuPian.getBoundingClientRect().top <= that.h && that.currentDomTuPian.isLoad != 1) {
            that.tupian.onload = function () {
                that.currentDomTuPian.src = that.currentDomTuPian.getAttribute('_src')
                that.currentDomTuPian.isLoad = 1
                that.currentDomTuPian = null
                that.tupian = null;
                console.log('载入醒来的')
                that.run()
            }
            that.tupian.onerror = function () {
                if (that.forceAbort) {
                    console.error('forceAbort:true:onerror里的');
                    // that.currentDomTuPian=null
                    // that.tupian=null;
                    that.forceAbort = false
                } else {
                    //img.src=img.getAttribute('_src')//竟然都已经错误的图片地址，就没必要放到src里
                    //img.src='/wrong.png'
                    that.currentDomTuPian.isLoad = 1
                    that.currentDomTuPian = null
                    that.tupian = null;
                    console.error('图片error路线', that.arrLazy.length)
                }
                that.run()
                console.error('aaaa图片error路线')
            }
            console.info('head11111111111111111111非首次加载并且待载图片滚动后依旧在当前屏幕,不用中断图片')
        } else {
            console.info('head2222222222222222正常读取完加载或来到全新屏幕,中断图片下载')
            if (that.tupian) {
                //来到全新的屏幕,把之前正在加载的图片进行终止
                console.log('有that.tupian', that.tupian.src)
                that.forceAbort = true;
                that.tupian.src = null;
                that.currentDomTuPian = null
                that.tupian = null;
            } else {
                console.log('没有that.tupian')
            }
            console.log('run,还剩余dom数', that.arrLazy.length)
            for (var i = 0; i < that.arrLazy.length; i++) {

                var img = that.arrLazy[i]
                if (img.getBoundingClientRect().top >= 0 && img.getBoundingClientRect().top <= that.h && img.isLoad != 1) {
                    console.log('for循环内部依次判断每个元素是否在屏幕内')
                    that.currentDomTuPian = img
                    that.tupian = new Image();
                    that.tupian.src = img.getAttribute('_src');
                    that.tupian.onload = function () {
                        img.src = img.getAttribute('_src')
                        img.isLoad = 1
                        //that.arrLazy.splice(i,1)
                        that.currentDomTuPian = null
                        that.tupian = null;
                        console.debug('图片加载完成11111')
                        that.run()
                    };
                    that.tupian.onerror = function () {
                        if (that.forceAbort) {
                            console.error('forceAbort:true:onerror里的');
                            // that.currentDomTuPian=null
                            // that.tupian=null;
                            that.forceAbort = false
                        } else {
                            //img.src=img.getAttribute('_src')//竟然都已经错误的图片地址，就没必要放到src里
                            //img.src='/wrong.png'
                            img.isLoad = 1
                            //that.arrLazy.splice(i,1)
                            that.currentDomTuPian = null
                            that.tupian = null;
                            console.error('图片error路线', that.arrLazy.length)
                        }
                        that.run()
                    };
                    break;
                    //退出循环原因:竟然有图片在屏幕中了,那么就等待onload完毕后再执行一下张,目的是图片加载完成后,
                    //整体高度会变化,在变化后的高度里重新循环
                }
            }
        }


    }
    this.run()
    this.init = function () {
        window.addEventListener('scroll', this.throttle(this.run.bind(this), 1000).bind(this), false)
    },
        this.update = function () {
            this.lazyImg = document.getElementsByClassName('lazy')
            this.arrLazy = []
            for (var i = 0; i < this.lazyImg.length; i++) {
                if (!this.lazyImg[i].isLoad) {
                    this.arrLazy.push(this.lazyImg[i]);
                }
            }
            console.log('gaga', this.arrLazy.length)
        }
    this.throttle = function (fn, delay, atleast) {
        var timer = null;
        var previous = null;
        return function () {
            var now = +new Date();
            if (!previous) previous = now;
            if (atleast && now - previous > atleast) {
                fn();
                // 重置上一次开始时间为本次结束时间
                previous = now;
                clearTimeout(timer);
            } else {
                clearTimeout(timer);
                timer = setTimeout(function () {
                    fn();
                    previous = null;
                }, delay);
            }
        }
    }
}
var cc = new lazyImg()
cc.init()

function init() { cc.init() }

document.getElementById('genxin').onclick = function () {
    cc.update()
}
document.getElementById('add').onclick = function () {
    document.getElementById('fff').innerHTML = "<img class='lazy' _src='http://img1.replays.net/war3.replays.net/uploads/body/2018/04/15241984276Ee.jpg'><img class='lazy' _src='http://img1.replays.net/war3.replays.net/uploads/body/2018/04/15241984276Ee.jpg'>"
}
</script>
</body>
</html>
